package com.example.xmlfactory.parse.pull;

import android.util.Xml;

import com.example.xmlfactory.parse.ClassMsg;
import com.example.xmlfactory.parse.Parser;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by huangbei on 2017/9/12.
 */

public class PullParser implements Parser{

    @Override
    public List parse(InputStream inputStream, Class cl) throws Exception {
        List list = new ArrayList();
        try{
            ClassMsg classMsg = new ClassMsg(cl);
            XmlPullParser parser = Xml.newPullParser(); //由android.util.Xml创建一个XmlPullParser实例
            parser.setInput(inputStream, "UTF-8");               //设置输入流 并指明编码方式

            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:

                        break;
                    case XmlPullParser.START_TAG:
                        String name = parser.getName();
                        if (name.equals(classMsg.getClassName())) {
                            classMsg.clearProperty();
                        }else if(classMsg.isProperty(name)){
                            eventType = parser.next();
                            classMsg.addValue(name,parser.getText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if (parser.getName().equals(classMsg.getClassName())) {
                            list.add(classMsg.generateObj());
                        }
                        break;
                }
                eventType = parser.next();
            }
            return list;

        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
